import json

import requests
import openpyxl
import logging

logging.basicConfig(filename='tokenlog.log', level=logging.INFO, encoding='utf-8')
# 定义接口 URL
api_url = "http://172.16.9.157:11562/global-user-domain/fjUserRegisterOrLogin"  # 测试环境
# api_url = "http://localhost:11562/global-user-domain/fjUserRegisterOrLogin"  # 本机

phone = 12100000001
token_num = 10  # 需要生成的token数量

# 请求头
headers = {
    'Content-Type': 'application/json'
}

# 创建 Excel 工作簿和工作表
wb = openpyxl.Workbook()
ws = wb.active

# 初始化行号
row_num = 1

# 循环发送 POST 请求获取数据
for _ in range(token_num):
    # 请求体
    payload = json.dumps({
        "data": {
            "phone": phone,
            "avatar": "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoIKzU04mcvyqopKGhgaDxEKwubkOWHH17q9gahWI68yGj2fYibwcAm6QZpSEQVuP3peniasPqvLEZg/132",
            "nickName": "压测造数据昵称",
            "gender": 0,
            "wxUserName": "压测造数据微信昵称"
        }
    })
    response = requests.post(api_url, data=payload, headers=headers)
    print(phone, response.text)
    logging.info(f'{phone}==={response.text}')

    if response.status_code == 200:
        data = response.json()  # 接口返回的是 JSON 数据
        extracted_token = data['data']['token']
        another_field_1 = data['data'].get('userId', '')
        another_field_2 = data['data']['bindSystemList'][0]['sourceUserId']
        # 将参数写入 Excel 表格
        ws.cell(row=row_num, column=1, value=extracted_token)
        ws.cell(row=row_num, column=2, value=another_field_1)
        ws.cell(row=row_num, column=3, value=another_field_2)
        row_num += 1
        phone = int(phone) + 1
    else:
        print(f"接口请求失败: {response.status_code}")
    # time.sleep(0.5)  # 为了避免请求过于频繁，添加延迟

# 保存 Excel 文件
wb.save("token.xlsx")
